# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '100051': {  # witch 支付宝（10---5000）
        'API_KEY': 'e0b242899cf50c671ccae0ef5d667655ef466592',
        'gateway': 'http://pay.dongfang999.com/Home/Pay/payForJson',
        'query_gateway': 'http://pay.dongfang999.com/Home/Pay/get_result2',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# notify_url + order_id + order_name + price + return_url + token + type + uid
def generate_sign(parameter, key):
    s = '{}{}{}{}{}{}{}{}'.format(parameter['notify_url'], parameter['order_id'],
                                  parameter['order_name'], parameter['price'],
                                  parameter['return_url'], key,
                                  parameter['type'], parameter['uid'])
    _LOGGER.info('feiniubaopay sign str: %s', s)
    return _gen_sign(s)


# order_id + order_uid + price + transaction_id + token
def generate_notify_sign(parameter, key):
    s = '{}{}{}{}{}'.format(parameter['order_id'], parameter['order_uid'],
                            parameter['price'], parameter['transaction_id'],
                            key)
    _LOGGER.info('feiniubaopay notify sign str: %s', s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('key')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("feiniubaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 1：微信支付；2：支付宝
def _get_pay_type(service):
    if service == 'alipay':
        return '2'
    return '2'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('price', str(int(pay_amount))),
        ('type', _get_pay_type(service)),
        ('notify_url', '{}/pay/api/{}/feiniubaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url',
         '{}/pay/api/{}/feiniubaopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('order_id', str(pay.id)),
        ('order_name', 'charge')
    ))
    parameter_dict['key'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("feiniubaopay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("feiniubaopay create rsp data: %s", response.text)
    data = json.loads(response.text)
    order_db.fill_third_id(str(pay.id), data['sys_order_id'])
    return {'charge_info': data['qrcode']}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("feiniubaopay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('feiniubaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['pay_num']
    total_fee = float(data['price'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '0000' and total_fee > 0.0:
        _LOGGER.info('feiniubaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('sys_order_id', pay_order.third_id),
    ))
    _LOGGER.info('feiniubaopay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('feiniubaopay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['code'])
        total_fee = float(pay_order.total_fee)
        trade_no = str(pay_order.third_id)

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '0000':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('feiniubaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
